import com.mysql.cj.jdbc.MysqlDataSource;

import javax.sql.DataSource;
import javax.xml.crypto.Data;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Scanner;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 19182
 * Date: 2025-08-12
 * Time: 20:29
 */
public class Jdbcdemo1 {
    public static void main(String[] args) throws SQLException {
        Scanner scanner = new Scanner(System.in);
        //1.创建数据源
        DataSource dataSource = new MysqlDataSource(); //找到数据库在哪里
        ((MysqlDataSource)dataSource).setURL("jdbc:mysql://127.0.0.1:3306/java117?characterEncoding=utf8&useSSL=false");
        ((MysqlDataSource)dataSource).setUser("root");
        ((MysqlDataSource)dataSource).setPassword("201754ljj");
        // 2. 和数据库服务器进行通信. 需要建立网络连接
        Connection connection = dataSource.getConnection();
        //3.构造SQL语句, 让用户来输入要插入的数据
        System.out.println("请你输入要插入的id:");
        int id = scanner.nextInt();
        System.out.println("请输入你要插入的name:");
        String name = scanner.next();
        String sql = "insert into student values(?, ?)"; //占位符, 占两个参数
        PreparedStatement preparedStatement = connection.prepareStatement(sql); //预处理sql,
        preparedStatement.setInt(1, id);
        preparedStatement.setString(2, name);
        //执行SQL语句, 把请求发给MySQL服务器
        int n = preparedStatement.executeUpdate();
        System.out.println("n = " + n);
        preparedStatement.close();;
        connection.close();;
    }
}
